//
//  CMPlayingViewController.m
//  CaesarMusic
//
//  Created by Caesar on 15/10/30.
//  Copyright © 2015年 Caesar. All rights reserved.
//

#import "CMPlayingViewController.h"
#import "UIView+AdjustFrame.h"
#import "CMMusicTool.h"
#import "CMMusic.h"
#import "CMAudioTool.h"


@interface CMPlayingViewController ()

/// 记录当前的音乐
@property (nonatomic, strong) CMMusic *playingMusic;

/// 进度的定时器
@property (nonatomic, strong) NSTimer *progressTimer;

@property (nonatomic, strong) AVAudioPlayer *player;

/// 歌手
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;
/// 歌名
@property (weak, nonatomic) IBOutlet UILabel *songLabel;
/// 歌手背景图片
@property (weak, nonatomic) IBOutlet UIImageView *singerIcon;
/// 歌曲时长
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
/// 拖动按钮
@property (weak, nonatomic) IBOutlet UIButton *sliderButton;
/// 拖动时显示时间
@property (weak, nonatomic) IBOutlet UILabel *showTimeLabel;
// 播放暂停按钮的属性
@property (weak, nonatomic) IBOutlet UIButton *playOrPauseButton;
/// 拖拽按钮与左边的距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sliderLeftConstraint;
/// 进度条背景点击
- (IBAction)tapProgressBackground:(UITapGestureRecognizer *)sender;
/// 拖拽滑块按钮
- (IBAction)panSliderButton:(UIPanGestureRecognizer *)sender;
/// 播放暂停按钮的点击
- (IBAction)playOrPauseButtonClick;
/// 上一首按钮的点击
- (IBAction)previousButtonClick;
/// 下一首按钮的点击
- (IBAction)nextButtonClick;
/// 退出按钮
- (IBAction)closeClik;

@end


@implementation CMPlayingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.showTimeLabel.layer.cornerRadius = 4.0;
    self.showTimeLabel.layer.masksToBounds = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - *************** 对控制器的操作 ***************

// 显示控制器
- (void)show{
    
    // 0.判断音乐是否发生改变
    if (self.playingMusic && self.playingMusic != [CMMusicTool playingMusic]) {
        [self stopPlayingMusic];
    }
    
    // 1.拿到 window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    window.userInteractionEnabled = NO;
    
    // 2.设置view 的 frame
    self.view.frame = window.bounds;
    
    // 3.见自身的 frame 添加到 window上
    [window addSubview:self.view];
    
    // 4.设置 self.view 的 y 值等于 window 高度
    self.view.y = self.view.height;
    
    // 5.给 self.view 添加动画
    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = 0;
    } completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
    }];
    
    // 开始播放音乐, 并且展示数据
    [self startPlayingMusic];
}

// 退出控制器
- (IBAction)closeClik {
    
    // 1.拿到 window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.userInteractionEnabled = NO;
    
    // 2.执行动画退出 window
    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = self.view.height;
    } completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
        
        // 3.移除定时器
        [self removeprogressTimer];
    }];
    
}

#pragma mark - *************** 对音乐播放器的控制 ***************

/// 开始播放音乐
- (void)startPlayingMusic {
    
    // 1.拿到正在播放的音乐数据
    CMMusic *playingMusic = [CMMusicTool playingMusic];
    
    if (playingMusic == self.playingMusic) {
        [self addProgressTimer];
        return;
    }

    self.playingMusic = playingMusic;
    
    // 2.设置界面数据
    self.songLabel.text = playingMusic.name;
    self.singerLabel.text = playingMusic.singer;
    self.singerIcon.image = [UIImage imageNamed:playingMusic.icon];
    
    // 3.播放音乐
    self.player =  [CMAudioTool playMusicWithName:self.playingMusic.filename];
    self.totalTimeLabel.text = [self stringWithTime:self.player.duration];
    
    // 4.添加定时器
    [self addProgressTimer];
    [self updateInfo];
    
    // 5.改变按钮的点击状态
    self.playOrPauseButton.selected = NO;
}


/// 停止播放音乐
- (void)stopPlayingMusic {
    
    /// 清除界面数据
    self.songLabel.text = nil;
    self.singerLabel.text = nil;
    self.singerIcon.image = [UIImage imageNamed:@"play_cover_pic_bg"];
    
    [CMAudioTool stopMusicWithName:self.playingMusic.filename];
}


#pragma mark - *************** 定时器的操作 ***************
// 添加定时器
- (void)addProgressTimer{
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateInfo) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
}

/// 移除定时器
- (void)removeprogressTimer{
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}

/// 随着播放进度更新进度条
-(void)updateInfo {
    NSLog(@"更新数据");
    
    // 1.计算播放比例
    CGFloat progerssRatio = self.player.currentTime / self.player.duration;
    
    // 2.更新滑块的位置
    self.sliderLeftConstraint.constant = progerssRatio * (self.view.width - self.sliderButton.width);
    
    // 3.更新滑块的文字
    NSString *currentTimerStr = [self stringWithTime:self.player.currentTime];
    [self.sliderButton setTitle:currentTimerStr forState:UIControlStateNormal];
}

/// 点击进度条时更新
- (IBAction)tapProgressBackground:(UITapGestureRecognizer *)sender {
    
    // 1.获取用户点击位置
    CGPoint point = [sender locationInView:sender.view];
    
    // 2.改变 sliderButton 的约束
    if(point.x <= self.sliderButton.width * 0.5){
        self.sliderLeftConstraint.constant = 0;
    } else if (point.x >= self.view.width - self.sliderButton.width * 0.5) {
        self.sliderLeftConstraint.constant = self.view.width - self.sliderButton.width -1 ;
    }else {
        self.sliderLeftConstraint.constant = point.x - self.sliderButton.width;
    }
    
    // 3.改变当前播放的时间currentTime
    CGFloat progerssRatio = self.sliderLeftConstraint.constant / (self.view.width - self.sliderButton.width);
    CGFloat currentTime = progerssRatio * self.player.duration;
    
    self.player.currentTime = currentTime;
    
    // 4.更新文字
    [self updateInfo];
}


/// 拖拽滑块按钮时更新
- (IBAction)panSliderButton:(UIPanGestureRecognizer *)sender {

    // 1.获取用户拖拽的位置
    CGPoint point = [sender translationInView:sender.view]; // 默认起始位置
    [sender setTranslation:CGPointZero inView:sender.view]; // 拖拽到的位置
    
    // 2.改变 sliderButton 的约束
    if(self.sliderLeftConstraint.constant + point.x <= 0){
        self.sliderLeftConstraint.constant = 0;
    }
    else if (self.sliderLeftConstraint.constant + point.x >= self.view.width - self.sliderButton.width) {
        self.sliderLeftConstraint.constant = self.view.width - self.sliderButton.width;
    }
    else {
        self.sliderLeftConstraint.constant += point.x;
    }
    
    // 3.获取拖拽进度的对应的播放时间
    CGFloat progerssRatio = self.sliderLeftConstraint.constant / (self.view.width - self.sliderButton.width);
    CGFloat currentTime = progerssRatio * self.player.duration;
    
    // 4.更新文字
    NSString *currentTimerStr = [self stringWithTime:currentTime];
    [self.sliderButton setTitle:currentTimerStr forState:UIControlStateNormal];
    
    // 5.监听拖拽手势状态
    if (sender.state == UIGestureRecognizerStateBegan) {
        // 5.1移除定时器
        [self removeprogressTimer];
        // 5.2让显示时间的 label显示
        self.showTimeLabel.hidden = NO;
    } else if (sender.state == UIGestureRecognizerStateEnded) {
        // 5.1更新播放时间
        self.player.currentTime = currentTime;
        // 5.2添加定时器
        [self addProgressTimer];
        // 5.3让显示时间的 label 取消隐藏
        self.showTimeLabel.hidden = YES;
    }
}

#pragma mark - *************** 播放/暂停/上一首/下一首按钮的点击 ***************
/// 播放活暂停按钮的点击
- (IBAction)playOrPauseButtonClick {
    self.playOrPauseButton.selected = !self.playOrPauseButton.selected;
    
    if (self.player.playing) {
        [self.player pause];
        [self removeprogressTimer];
    } else {
        [self.player play];
        [self addProgressTimer];
    }
}

/// 上一首音乐的点击
- (IBAction)previousButtonClick {
    [self stopPlayingMusic];
    [CMMusicTool previousMusic];
    [self startPlayingMusic];
}

/// 下一首音乐播放的点击
- (IBAction)nextButtonClick {
        [self stopPlayingMusic];
        [CMMusicTool nextMusic];
        [self startPlayingMusic];
}


#pragma mark - *************** 私有方法 ***************
- (NSString *)stringWithTime:(NSTimeInterval)time {
    
    NSInteger minute = time / 60;
    NSInteger second = (NSInteger)time % 60;
    return [NSString stringWithFormat:@"%02ld:%02ld", minute, second];
}

@end
